package com.ultrapower.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.result.Tree;
import com.ultrapower.commons.utils.JsonUtils;
import com.ultrapower.mapper.OrganizationMapper;
import com.ultrapower.model.Organization;
import com.ultrapower.service.IOrganizationService;

/**
 *
 * Organization 表数据服务层接口实现类
 *
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements IOrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;
    
    @Override
    public List<Tree> selectTree(Long userId) {
        List<Organization> organizationList = selectTreeGrid();
        
        List<Tree> trees = new ArrayList<Tree>();
        if (organizationList != null) {
            for (Organization organization : organizationList) {
                Tree tree = new Tree();
                tree.setId(organization.getId());
                tree.setName(organization.getName());
                tree.setPid(organization.getPid());
                trees.add(tree);
            }
        }
        for(int i=0;i<trees.size();i++) {
        	trees.get(i).setChildren(new ArrayList<Tree>());
        	 for(int j=0;j<trees.size();j++) {
        		 if(trees.get(i).getId()==trees.get(j).getPid()) {
        			 trees.get(i).getChildren().add(trees.get(j)); 
        		 }
        	 }
        }
        return trees;
    }

    @Override
    public List<Organization> selectTreeGrid() {
        EntityWrapper<Organization> wrapper = new EntityWrapper<Organization>();
        wrapper.orderBy("seq");
        return organizationMapper.selectList(wrapper);
    }

	@Override
	public void selectDataGrid(PageInfo pageInfo) {
		Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageInfo.getNowpage(), pageInfo.getSize());
        page.setOrderByField(pageInfo.getSort());
        page.setAsc(pageInfo.getOrder().equalsIgnoreCase("asc"));
        List<Map<String, Object>> list = organizationMapper.selectOrgPage(page, pageInfo.getCondition());
        pageInfo.setData(list);
        pageInfo.setCount(page.getTotal());
	}
	
	@Override
	public Organization selectOrgByUserId(Long userId) {
		return organizationMapper.selectOrgByUserId(userId);
	}


}